package com.patentbackend.patentmanage.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

public class FileUtils {

    public static String saveFile(MultipartFile file, String uploadDir, String subDirectory) throws IOException {
        // 创建存储目录
        Path uploadPath = Paths.get(uploadDir + "/" + subDirectory);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
        Path filePath = uploadPath.resolve(fileName);

        // 保存文件
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

        // 返回文件路径
        return subDirectory + "/" + fileName;
    }

    public static byte[] readFile(String uploadDir, String filePath) throws IOException {
        Path fileLocation = Paths.get(uploadDir).resolve(filePath);
        return Files.readAllBytes(fileLocation);
    }

    public static void deleteFile(String uploadDir, String filePath) throws IOException {
        Path fileLocation = Paths.get(uploadDir).resolve(filePath);
        Files.deleteIfExists(fileLocation);
    }

    public static String getFileExtension(String fileName) {
        if (fileName == null) {
            return null;
        }
        int lastIndexOf = fileName.lastIndexOf(".");
        if (lastIndexOf == -1) {
            return null;
        }
        return fileName.substring(lastIndexOf + 1);
    }
}